#include "controls.h"
#include <string.h>
#include <pspkernel.h>

PSP_MODULE_INFO("control_bridge", 0x1006, 1, 1);
PSP_MAIN_THREAD_ATTR(0);

int sceCtrlReadBufferPositive371(SceCtrlData *pad_data, int count);

unsigned int pressed = 0;
unsigned int released = 0;
unsigned int held = 0;
unsigned int last_held = 0;

NewCtrlData read_controls()
{
	u32 prevk = pspSdkSetK1(0);
	SceCtrlData pad;
	sceCtrlSetSamplingCycle(0);
	sceCtrlSetSamplingMode(1);
    if (sceKernelDevkitVersion() < 0x03070110)
        sceCtrlReadBufferPositive(&pad,1);
    else
        sceCtrlReadBufferPositive371(&pad, 1);

	pressed = ~last_held & pad.Buttons;
	released = last_held & ~pad.Buttons;

	held = pad.Buttons;
	last_held = pad.Buttons;

	NewCtrlData data;

	data.data = pad;

	data.held = held;
	data.last_held = last_held;

	data.pressed = pressed;
	data.released = released;

    pspSdkSetK1(prevk);
	return data;
}
SceCtrlData get_controls_sce()
{
	u32 prevk = pspSdkSetK1(0);
	SceCtrlData pad;
	sceCtrlSetSamplingCycle(0);
	sceCtrlSetSamplingMode(1);
    if (sceKernelDevkitVersion() < 0x03070110)
        sceCtrlReadBufferPositive(&pad,1);
    else
        sceCtrlReadBufferPositive371(&pad, 1);
    pspSdkSetK1(prevk);
	return pad;
}
int read_controls_sce(SceCtrlData *pad_data, int count)
{
	int i;
	u32 prevk = pspSdkSetK1(0);
	sceCtrlSetSamplingCycle(0);
	sceCtrlSetSamplingMode(1);
	i = sceCtrlReadBufferPositive(pad_data,count);
	pspSdkSetK1(prevk);
	return i;
}

int headphone_exist()
{
	return sceHprmIsHeadphoneExist();
}

int remote_exist()
{
	return sceHprmIsRemoteExist();
}

int microphone_exist()
{
	return sceHprmIsMicrophoneExist();
}

u32 hprm_last_held = 0;
u32 hprm_held = 0;
u32 hprm_released = 0;
u32 hprm_pressed = 0;

NewHprmData read_hprm()
{
	u32 remote;
	sceHprmPeekCurrentKey(&remote);
	hprm_pressed = ~hprm_last_held & remote;
	hprm_released = hprm_last_held & ~remote;
	hprm_held = remote;
	hprm_last_held = remote;

	NewHprmData data;

	data.keydata = remote;

	data.pressed = hprm_pressed;
	data.released = hprm_released;

	data.held = hprm_held;
	data.last_held = hprm_last_held;

	return data;
}
u32 read_hprm_sce()
{
	u32 remote;
	sceHprmPeekCurrentKey(&remote);
	return remote;
}

int module_start(SceSize args, void *argp)
{
	return 0;
}

int module_stop()
{
	return 0;
}
